#!/bin/bash

# 显示彩色输出
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# 设置镜像信息
IMAGE_REGISTRY="1.94.151.57:85"
IMAGE_REPO="chaos-mesh"
IMAGE_NAME="extralindextest"
IMAGE_TAG=$(date +"%Y%m%d%H%M%S")
FULL_IMAGE_NAME="${IMAGE_REGISTRY}/${IMAGE_REPO}/${IMAGE_NAME}:${IMAGE_TAG}"
LATEST_IMAGE_NAME="${IMAGE_REGISTRY}/${IMAGE_REPO}/${IMAGE_NAME}:latest"

# 命名空间
NAMESPACE="chaos-test"

echo -e "${YELLOW}开始构建和部署流程...${NC}"

# 确保k8s目录存在
mkdir -p k8s

# 1. 构建项目
echo -e "${YELLOW}1. 构建Java项目...${NC}"
mvn clean package -DskipTests
if [ $? -ne 0 ]; then
  echo -e "${RED}Maven构建失败${NC}"
  exit 1
fi
echo -e "${GREEN}Maven构建成功${NC}"

# 2. 构建Docker镜像
echo -e "${YELLOW}2. 构建Docker镜像: ${FULL_IMAGE_NAME}${NC}"
docker build -t ${FULL_IMAGE_NAME} .
if [ $? -ne 0 ]; then
  echo -e "${RED}Docker镜像构建失败${NC}"
  exit 1
fi
docker tag ${FULL_IMAGE_NAME} ${LATEST_IMAGE_NAME}
echo -e "${GREEN}Docker镜像构建成功${NC}"

# 3. 推送Docker镜像
echo -e "${YELLOW}3. 推送Docker镜像到仓库...${NC}"
docker push ${FULL_IMAGE_NAME}
docker push ${LATEST_IMAGE_NAME}
if [ $? -ne 0 ]; then
  echo -e "${RED}Docker镜像推送失败${NC}"
  exit 1
fi
echo -e "${GREEN}Docker镜像推送成功${NC}"

# 4. 部署到Kubernetes
echo -e "${YELLOW}4. 部署到Kubernetes...${NC}"

# 创建命名空间（如果不存在）
echo -e "${YELLOW}   检查并创建命名空间 ${NAMESPACE}...${NC}"
kubectl get namespace ${NAMESPACE} > /dev/null 2>&1
if [ $? -ne 0 ]; then
  kubectl create namespace ${NAMESPACE}
  if [ $? -ne 0 ]; then
    echo -e "${RED}创建命名空间失败${NC}"
    exit 1
  fi
  echo -e "${GREEN}命名空间 ${NAMESPACE} 创建成功${NC}"
else
  echo -e "${GREEN}命名空间 ${NAMESPACE} 已存在${NC}"
fi

# 应用ConfigMap
echo -e "${YELLOW}   应用ConfigMap...${NC}"
kubectl apply -f k8s/configmap.yaml
if [ $? -ne 0 ]; then
  echo -e "${RED}ConfigMap部署失败${NC}"
  exit 1
fi

# 应用Deployment和Service
echo -e "${YELLOW}   应用Deployment和Service...${NC}"
kubectl apply -f k8s/deployment.yaml
if [ $? -ne 0 ]; then
  echo -e "${RED}Deployment部署失败${NC}"
  exit 1
fi

echo -e "${GREEN}Kubernetes部署成功${NC}"

# 5. 检查部署状态
echo -e "${YELLOW}5. 检查部署状态...${NC}"
echo -e "${YELLOW}   等待Deployment就绪...${NC}"
kubectl rollout status deployment/extralindextest -n ${NAMESPACE}
if [ $? -ne 0 ]; then
  echo -e "${RED}Deployment部署未就绪，请检查日志${NC}"
  exit 1
fi

echo -e "${YELLOW}   检查Service...${NC}"
kubectl get svc extralindextest -n ${NAMESPACE}

echo -e "${GREEN}部署完成！应用现在可以通过 NodePort 30085 访问${NC}"
echo -e "${GREEN}访问地址: http://<节点IP>:30085${NC}" 